import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { isTreeDataHasMultiLevel, ITree } from '../../utils/utility';
import { TreeNode } from './TreeNode';
import { VirtualizedTree } from './VirtualizedTree';

export interface ITreeProps {
  treeData: ITree[];
  onChange?: (treeData: ITree[]) => void;
  style?: React.CSSProperties;
}

export class Tree extends React.Component<ITreeProps, {}> {
  public static Node = TreeNode;

  public static Virtualized = VirtualizedTree;

  public static propTypes = {
    treeData: PropTypes.arrayOf(TreeNode.propTypes.treeNode),
    onChange: PropTypes.func,
    style: PropTypes.object,
  };

  constructor(props: ITreeProps) {
    super(props);
  }

  public handleChange(tree: ITree, index: number) {
    if (this.props.onChange) {
      this.props.onChange([
        ...this.props.treeData.slice(0, index),
        tree,
        ...this.props.treeData.slice(index + 1),
      ]);
    }
  }

  public render() {
    const classes = {
      'br-tree': true,
      'br-tree--list': !isTreeDataHasMultiLevel(this.props.treeData),
    };
    return (
      <ul className={classNames(classes)} style={this.props.style}>
        {
          this.props.treeData.map((tree, index) => {
            return (
              <TreeNode
                key={tree.key}
                treeNode={tree}
                onChange={(treeNode) => this.handleChange(treeNode, index)}
              />
            );
          })
        }
      </ul>
    );
  }
}
